<template>
  <div class="doctor-schedule-page">
    <!-- 顶部导航 -->
    <div class="header">
      <div class="back-btn" @click="handleBack">
        <el-icon><ArrowLeft /></el-icon>
        返回
      </div>
      <div class="page-title">{{ departmentName }}门诊</div>
    </div>

    <!-- 科室信息 -->
    <div class="department-info">
      <div class="department-title">{{ departmentName }}门诊</div>
      <div class="hospital-name">{{ hospitalInfo.hospitalName }}</div>
    </div>

    <div class="divider"></div>

    <!-- 日期选择 -->
    <div class="date-section">
      <div class="section-title">日期选择</div>

      <!-- 加载状态 -->
      <div v-if="scheduleLoading" class="loading-container">
        <el-skeleton :rows="2" animated />
      </div>

      <!-- 日期列表 -->
      <div v-else class="date-list">
        <div class="date-category">
          <div class="category-title">近期</div>
          <div class="dates-grid">
            <div
                v-for="date in recentDates"
                :key="date.date"
                class="date-item"
                :class="{
                'available': date.status === 'available',
                'full': date.status === 'full',
                'selected': selectedDate === date.date
              }"
                @click="handleDateSelect(date)"
            >
              <div class="date-day">{{ date.dayOfWeek }}</div>
              <div class="date-number">{{ date.date.split('-')[2] }}</div>
              <div class="date-status">{{ getStatusText(date.status) }}</div>
            </div>
          </div>
        </div>

        <div class="date-category">
          <div class="category-title">下周</div>
          <div class="dates-grid">
            <div
                v-for="date in nextWeekDates"
                :key="date.date"
                class="date-item"
                :class="{
                'available': date.status === 'available',
                'full': date.status === 'full',
                'selected': selectedDate === date.date
              }"
                @click="handleDateSelect(date)"
            >
              <div class="date-day">{{ date.dayOfWeek }}</div>
              <div class="date-number">{{ date.date.split('-')[2] }}</div>
              <div class="date-status">{{ getStatusText(date.status) }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="divider"></div>

    <!-- 医生列表 -->
    <div class="doctors-section">
      <div class="section-title">医生列表</div>

      <!-- 加载状态 -->
      <div v-if="doctorsLoading" class="loading-container">
        <el-skeleton :rows="4" animated />
      </div>

      <!-- 医生列表 -->
      <div v-else class="doctors-list">
        <div
            v-for="doctor in filteredDoctors"
            :key="doctor.doctorId"
            class="doctor-card"
        >
          <div class="doctor-info">
            <div class="doctor-name-title">
              <span class="doctor-name">{{ doctor.doctorName }}</span>
              <span class="doctor-title">{{ doctor.title }}</span>
            </div>
            <div class="doctor-department">{{ departmentName }}门诊</div>
            <div class="doctor-hospital">坐诊：{{ hospitalInfo.hospitalName }}</div>
          </div>

          <div class="doctor-actions">
            <div class="appointment-count">{{ doctor.appointmentCount || 0 }}人预约</div>
            <div class="schedule-status" :class="getScheduleStatusClass(doctor.scheduleStatus)">
              {{ getScheduleStatusText(doctor.scheduleStatus) }}
            </div>
            <el-button
                type="primary"
                size="small"
                :disabled="doctor.scheduleStatus !== 'available'"
                @click="handleMakeAppointment(doctor)"
            >
              预约
            </el-button>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="filteredDoctors.length === 0" class="empty-state">
          <el-empty :description="selectedDate ? '该日期暂无医生排班' : '暂无医生数据'" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { getHospital } from '@/api/institution/hospital.js'
import { listSchedule } from '@/api/scheduling/schedule.js'
import { listDoctor } from '@/api/medical/doctor.js'

const router = useRouter()
const route = useRoute()

const hospitalId = ref('')
const departmentId = ref('')
const departmentName = ref('')
const hospitalInfo = ref({})
const scheduleLoading = ref(false)
const doctorsLoading = ref(false)
const selectedDate = ref('')
const schedules = ref([])
const doctors = ref([])

// 页面加载时初始化数据
onMounted(() => {
  hospitalId.value = route.params.hospitalId
  departmentId.value = route.params.departmentId
  departmentName.value = route.query.departmentName || '科室'

  loadHospitalData()
  loadSchedules()
  loadDoctors()
})

// 计算近期日期（今天+接下来6天）
const recentDates = computed(() => {
  return generateDateRange(0, 6)
})

// 计算下周日期
const nextWeekDates = computed(() => {
  return generateDateRange(7, 13)
})

// 过滤出选定日期有排班的医生
const filteredDoctors = computed(() => {
  if (!selectedDate.value) {
    return doctors.value.map(doctor => ({
      ...doctor,
      scheduleStatus: 'no_date'
    }))
  }

  return doctors.value.map(doctor => {
    const doctorSchedules = schedules.value.filter(
        schedule => schedule.doctorId === doctor.doctorId && schedule.scheduleDate === selectedDate.value
    )

    let scheduleStatus = 'no_schedule'
    if (doctorSchedules.length > 0) {
      const hasAvailable = doctorSchedules.some(schedule =>
          schedule.availableSlots > 0 && (schedule.availableSlots > (schedule.appointmentCount || 0))
      )
      scheduleStatus = hasAvailable ? 'available' : 'full'
    }

    return {
      ...doctor,
      scheduleStatus
    }
  }).filter(doctor => doctor.scheduleStatus !== 'no_schedule')
})

// 生成日期范围
const generateDateRange = (startDays, endDays) => {
  const dates = []
  const today = new Date()

  for (let i = startDays; i <= endDays; i++) {
    const date = new Date(today)
    date.setDate(today.getDate() + i)

    const dateStr = formatDate(date)

    // 查找当天的所有排班
    const daySchedules = schedules.value.filter(s => s.scheduleDate === dateStr)

    let status = 'no_schedule'
    if (daySchedules.length > 0) {
      // 如果当天有任何可预约的时段，状态为可约
      const hasAvailable = daySchedules.some(schedule =>
          schedule.availableSlots > 0 && (schedule.availableSlots > (schedule.appointmentCount || 0))
      )
      status = hasAvailable ? 'available' : 'full'
    }

    dates.push({
      date: dateStr,
      dayOfWeek: getDayOfWeek(date.getDay()),
      status: status
    })
  }

  return dates
}

// 格式化日期为 YYYY-MM-DD
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 获取星期几
const getDayOfWeek = (day) => {
  const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  return days[day]
}

// 加载医院数据
const loadHospitalData = async () => {
  try {
    const response = await getHospital(hospitalId.value)
    hospitalInfo.value = response.data || {}
  } catch (error) {
    console.error('加载医院数据失败:', error)
    ElMessage.error('加载医院数据失败')
  }
}

// 加载排班数据
const loadSchedules = async () => {
  try {
    scheduleLoading.value = true

    // 计算日期范围：从今天开始到未来13天（覆盖近期和下周）
    const today = new Date()
    const startDate = formatDate(today)
    const endDate = formatDate(new Date(today.getTime() + 13 * 24 * 60 * 60 * 1000))

    const query = {
      hospitalId: hospitalId.value,
      departmentId: departmentId.value,
      startDate: startDate,
      endDate: endDate
    }

    const response = await listSchedule(query)

    // 根据接口返回数据结构调整
    if (response.data && Array.isArray(response.data)) {
      schedules.value = response.data
    } else if (response.rows && Array.isArray(response.rows)) {
      schedules.value = response.rows
    } else {
      schedules.value = []
      console.warn('排班接口返回数据格式异常:', response)
    }

  } catch (error) {
    console.error('加载排班数据失败:', error)
    ElMessage.error('加载排班数据失败')
    schedules.value = []
  } finally {
    scheduleLoading.value = false
  }
}

// 加载医生数据
const loadDoctors = async () => {
  try {
    doctorsLoading.value = true

    const query = {
      hospitalId: hospitalId.value,
      departmentId: departmentId.value
    }

    const response = await listDoctor(query)

    if (response.data && Array.isArray(response.data)) {
      doctors.value = response.data
    } else if (response.rows && Array.isArray(response.rows)) {
      doctors.value = response.rows
    } else {
      doctors.value = []
      console.warn('医生接口返回数据格式异常:', response)
    }

  } catch (error) {
    console.error('加载医生数据失败:', error)
    ElMessage.error('加载医生数据失败')
    doctors.value = []
  } finally {
    doctorsLoading.value = false
  }
}

// 获取状态显示文本
const getStatusText = (status) => {
  const statusMap = {
    'available': '可约',
    'full': '约满',
    'no_schedule': '无排班'
  }
  return statusMap[status] || '未知'
}

// 获取排班状态样式类
const getScheduleStatusClass = (status) => {
  const classMap = {
    'available': 'available',
    'full': 'full',
    'no_schedule': 'no-schedule',
    'no_date': 'no-date'
  }
  return classMap[status] || 'no-date'
}

// 获取排班状态文本
const getScheduleStatusText = (status) => {
  const textMap = {
    'available': '可约',
    'full': '约满',
    'no_schedule': '无排班',
    'no_date': '选择日期'
  }
  return textMap[status] || '未知'
}

// 选择日期
const handleDateSelect = (date) => {
  if (date.status === 'available' || date.status === 'full') {
    selectedDate.value = date.date
  } else {
    ElMessage.warning('该日期无排班，请选择其他日期')
  }
}

// 预约医生
const handleMakeAppointment = (doctor) => {
  if (!selectedDate.value) {
    ElMessage.warning('请先选择预约日期')
    return
  }

  if (doctor.scheduleStatus !== 'available') {
    ElMessage.warning('该医生在当前日期不可预约')
    return
  }

  // 跳转到预约确认页面
  router.push({
    path: `/medical/appointment/${hospitalId.value}/${departmentId.value}/${doctor.doctorId}`,
    query: {
      date: selectedDate.value,
      doctorName: doctor.doctorName,
      departmentName: departmentName.value,
      hospitalName: hospitalInfo.value.hospitalName
    }
  })
}

// 返回上一页
const handleBack = () => {
  router.back()
}
</script>

<style scoped lang="scss">
.doctor-schedule-page {
  min-height: 100vh;
  background: #f8f9fa;
}

// 顶部导航
.header {
  background: white;
  padding: 16px;
  display: flex;
  align-items: center;
  gap: 12px;
  border-bottom: 1px solid #f0f0f0;

  .back-btn {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 14px;
    color: #409eff;
    cursor: pointer;

    &:hover {
      opacity: 0.8;
    }
  }

  .page-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }
}

// 科室信息
.department-info {
  background: white;
  padding: 16px;

  .department-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin-bottom: 8px;
  }

  .hospital-name {
    font-size: 14px;
    color: #666;
  }
}

// 分隔线
.divider {
  height: 8px;
  background: #f0f2f5;
}

// 日期区域
.date-section {
  background: white;
  padding: 16px;

  .section-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin-bottom: 16px;
    padding-left: 8px;
    position: relative;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 4px;
      height: 16px;
      background: #409eff;
      border-radius: 2px;
    }
  }
}

// 日期列表
.date-list {
  .date-category {
    margin-bottom: 20px;

    .category-title {
      font-size: 14px;
      font-weight: 500;
      color: #666;
      margin-bottom: 12px;
    }

    .dates-grid {
      display: grid;
      grid-template-columns: repeat(7, 1fr);
      gap: 8px;

      .date-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 12px 8px;
        border: 1px solid #e8e8e8;
        border-radius: 8px;
        cursor: pointer;
        transition: all 0.3s ease;

        .date-day {
          font-size: 12px;
          color: #999;
          margin-bottom: 4px;
        }

        .date-number {
          font-size: 16px;
          font-weight: 500;
          color: #333;
          margin-bottom: 4px;
        }

        .date-status {
          font-size: 11px;
        }

        // 可预约状态
        &.available {
          border-color: #409eff;
          background: #f0f7ff;

          .date-status {
            color: #409eff;
          }

          &:hover {
            background: #409eff;
            color: white;

            .date-day,
            .date-number,
            .date-status {
              color: white;
            }
          }
        }

        // 已约满状态
        &.full {
          border-color: #f56c6c;
          background: #fef0f0;

          .date-status {
            color: #f56c6c;
          }
        }

        // 选中状态
        &.selected {
          background: #409eff;
          color: white;
          border-color: #409eff;

          .date-day,
          .date-number,
          .date-status {
            color: white;
          }
        }

        // 无排班状态
        &:not(.available):not(.full) {
          background: #f5f5f5;
          border-color: #ddd;
          cursor: not-allowed;

          .date-day,
          .date-number {
            color: #ccc;
          }

          .date-status {
            color: #999;
          }
        }
      }
    }
  }
}

// 医生区域
.doctors-section {
  background: white;
  padding: 16px;

  .section-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
    margin-bottom: 16px;
    padding-left: 8px;
    position: relative;

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
      width: 4px;
      height: 16px;
      background: #409eff;
      border-radius: 2px;
    }
  }
}

// 加载状态
.loading-container {
  padding: 20px 0;
}

// 空状态
.empty-state {
  padding: 40px 0;
}

// 医生列表
.doctors-list {
  .doctor-card {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .doctor-info {
      flex: 1;

      .doctor-name-title {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 8px;

        .doctor-name {
          font-size: 16px;
          font-weight: 600;
          color: #333;
        }

        .doctor-title {
          font-size: 12px;
          color: #666;
          background: #f5f5f5;
          padding: 2px 6px;
          border-radius: 4px;
        }
      }

      .doctor-department {
        font-size: 14px;
        color: #666;
        margin-bottom: 4px;
      }

      .doctor-hospital {
        font-size: 12px;
        color: #999;
      }
    }

    .doctor-actions {
      display: flex;
      flex-direction: column;
      align-items: flex-end;
      gap: 8px;

      .appointment-count {
        font-size: 12px;
        color: #999;
      }

      .schedule-status {
        font-size: 13px;
        padding: 2px 8px;
        border-radius: 4px;

        &.available {
          color: #67c23a;
          background: #f0f9ff;
        }

        &.full {
          color: #f56c6c;
          background: #fef0f0;
        }

        &.no-schedule {
          color: #e6a23c;
          background: #fdf6ec;
        }

        &.no-date {
          color: #909399;
          background: #f4f4f5;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .header {
    padding: 12px;
  }

  .department-info {
    padding: 12px;

    .department-title {
      font-size: 16px;
    }
  }

  .date-section {
    padding: 12px;

    .dates-grid {
      grid-template-columns: repeat(4, 1fr) !important;
      gap: 6px;

      .date-item {
        padding: 8px 4px;

        .date-day {
          font-size: 11px;
        }

        .date-number {
          font-size: 14px;
        }

        .date-status {
          font-size: 10px;
        }
      }
    }
  }

  .doctors-section {
    padding: 12px;
  }

  .doctor-card {
    padding: 12px !important;
    flex-direction: column;
    align-items: flex-start !important;
    gap: 12px;

    .doctor-actions {
      width: 100%;
      flex-direction: row !important;
      justify-content: space-between;
      align-items: center;
    }
  }
}
</style>